(function($) {
    $(document).ready(function() {
    	// start modal div
		var content = '<div id="member_detail_modal" class="modal">';
		
		// start dialog
		content += '<div class="modal-dialog">';
		
		// start content
		content += '<div class="modal-content">';
	
		// header
		content += '<div class="modal-header">';
		content += '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>';
		content += '<h4 class="modal-title">&nbsp</h4>';
		content += '</div>';
		
		// body
		content += '<div class="modal-body"></div>';
		
		// footer
		content += '<div class="modal-footer"></div>';
		
		// close content
		content += '</div>';
		
		// close dialog
		content += '</div>';
		
		// close modal div
		content += '</div>';
		$('body').append(content);
		
		var $member_detail_modal = $('#member_detail_modal');
		var $member_detail_modal_title = $member_detail_modal.find('.modal-title');
		var $member_detail_modal_body = $member_detail_modal.find('.modal-body');
		var $member_detail_modal_footer = $member_detail_modal.find('.modal-footer');
		
		$member_detail_modal.on('shown.bs.modal', function () {
			$member_detail_modal_body.find('form').ajaxForm({ 
				delegation: true,
	    		target: '#member_detail_modal .modal-body',
		        'beforeSubmit' : function(arr, form, options) { 
					$('.holder-required').removeClass('holder-required');
					$('span.message').remove();
				},
		        'success' : function(data){
	
		        }
		    });
		});
		
		$member_detail_modal.on('hide.bs.modal', function () {
			$member_detail_modal_title.html();
			$member_detail_modal_body.html();
		});
		
		var prev_data = '[]';
	    $("#tree").jstree({ 
        	"core" : {
        		"animation" : 0,
				"themes" : { 
					"variant" : "large"
				},
				"data" : {
					"type" : "GET",
                    "global" : false,
					"url" : function (node) {
						return $("#tree").data('load-link');
				    },
				    'data' : function (node) {
				    	if(node.id === '#'){
							return { 
	                            "operation" : "GetRoot", 
	                            "id" : $("#tree").data('root')
	                        };
						}
						else{
							return { 
	                            "operation" : "GetChildren", 
	                            "id" : node.id.replace("node_","")
	                        };
						}
				    },
				    'dataFilter': function(data, type) {
				    	var parsed_data = JSON.parse(data);
				    	if(parsed_data.result == 'success'){
				    		prev_data = JSON.stringify(parsed_data.root);
				    		return prev_data;
				    	}
				    	else{
				    		alert(parsed_data.msg);
				    		return '[]';
				    	}
				    },
				    'error': function(xhr) {
						alert(ss.i18n._t('PersonalSponsorPage.ERROR_LOADING_TREE', 'Error occur while load these tree, please try again.'));
				    }
				}
        	},
            // List of active plugins
            "plugins" : [ 
                "search", "types"
            ],
            // Configuring the search plugin
            "search" : {
                // As this has been a common question - async search
                // Same as above - the `ajax` config option is actually jQuery's AJAX object
                "ajax" : function (str, callback) {
                	$.getJSON($("#tree").data('load-link'), {"operation" : "Search", "id" : str})
    				.done(function (data) {
       					callback(data); // all jstree needs is that you invoke callback with the above mentioned array
    				});
				}
            },
            // Using types - most of the time this is an overkill
            // read the docs carefully to decide whether you need types
			"types" : {
				"default" : {
					// If we specify an icon for the default type it WILL OVERRIDE the theme icons
					"icon" : "glyphicon glyphicon-user"
				}
			}
        })
        .bind("select_node.jstree", function (e, obj) {
        	if(obj.node.data.id > 0 && obj.node.data.id != undefined){
        		var url = $("#tree").data('member-link');
        		var title = 'Member Details';
        		
        		$member_detail_modal.on('show.bs.modal', function () {
					$member_detail_modal_title.text(title);
				});
				
				$.get(url, {'id': obj.node.data.id}, function(data) {
				    $member_detail_modal_body.html(data);
				    $member_detail_modal.modal('show');
				    
				}).fail(function() {
					$member_detail_modal_body.html('<p>' + ss.i18n._t('PersonalSponsorPage.ERROR_LOADING_MEMBER_DETAILS', 'Error occur while load member details, please try again.') +'</p>');
					$member_detail_modal.modal('show');
				});
        	}
        });
        
        $("#treemenu").find('a').live('click', function(e) {
        	e.preventDefault();
			switch(this.id) {
				case "search":
					var username = $("#search_text").val();
					if(username != '' && username != undefined){
						$.getJSON($("#tree").data('load-link'), {"operation" : "Check", "id" : username})
	    				.done(function (data) {
	    					if(data.result == 'success'){
	       						$("#tree").data('root', username);
								$("#tree").jstree(true).deselect_all();
								$("#tree").jstree(true).refresh();
							}
							else{
								alert(data.msg);
								$("#search_text").val('');
							}
	    				});
					}
					break;
				case "clear_search":
					$("#search_text").val('');
					$("#tree").data('root', '');
					$("#tree").jstree(true).deselect_all();
					$("#tree").jstree(true).refresh();
					break;
				case "refresh":
					$("#tree").jstree(true).deselect_all();
					$("#tree").jstree(true).refresh();
					break;
				case "open_all":
					$("#tree").jstree(true).open_all();
					break;
				case "close_all":
					$("#tree").jstree(true).close_all();
					break;
				case "search_text": break;
				default:
					$("#tree").jstree(this.id);
					break;
			}
		});
    });
})(jQuery);